package org.ltc.alliance.service.comment;

import org.ltc.alliance.constant.ErrorConst;
import org.ltc.alliance.constant.PowerConst;
import org.ltc.alliance.constant.StatusConst;
import org.ltc.alliance.constant.VisibleConst;
import org.ltc.alliance.dao.CommentDao;
import org.ltc.alliance.exception.BusinessException;
import org.ltc.alliance.model.CommentDomain;
import org.ltc.alliance.service.clubuser.ClubUserService;
import org.ltc.alliance.service.power.PowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService{
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private ClubUserService clubUserService;
    @Autowired
    private PowerService powerService;

    @Override
    public void saveCommentInfo(CommentDomain comment) {
        clubUserService.userInClub(comment.getCid(), comment.getUid());
        comment.setMstatus(StatusConst.Comment.NORMAL);
        commentDao.saveCommentInfo(comment);
    }

    @Override
    public List<CommentDomain> getComments(Integer uid, Integer cid, StatusConst.Comment status) {
        List<CommentDomain> commentResult = commentDao.getCommentList(cid, status, VisibleConst.ALL);
        List<CommentDomain> commentClub = commentDao.getCommentList(cid, status, VisibleConst.CLUB);
        List<CommentDomain> commentManager = commentDao.getCommentList(cid, status, VisibleConst.MANAGER);
        if (clubUserService.userIsInClub(cid, uid)) {
            commentResult.addAll(commentClub);
            PowerConst power = powerService.getPower(uid, cid);
            if (null != power) {
                if (power.equals(PowerConst.RELEASER) || power.equals(PowerConst.MANAGER)) {
                    commentResult.addAll(commentManager);
                }
            }
        }
        return commentResult;
    }

    @Override
    public void alterStatusByMid(Integer mid, StatusConst.Comment status) {
        this.commentIdExist(mid);
        CommentDomain comment = commentDao.getCommentByMid(mid);
        if (comment.getMstatus().equals(status)){
            throw new BusinessException(ErrorConst.Comment.STATUS_ALTER_MISMATCH);
        }
        commentDao.alterStatusByMid(mid, status);
    }

    @Override
    public void commentIdExist(Integer mid) {
        CommentDomain comment = commentDao.getCommentByMid(mid);
        if (null == comment) {
            throw new BusinessException(ErrorConst.Comment.COMMENT_ID_NOT_EXIST);
        }
    }

    @Override
    public void commentIdNotExist(Integer mid) {
        CommentDomain comment = commentDao.getCommentByMid(mid);
        if (null != comment) {
            throw new BusinessException(ErrorConst.Comment.COMMENT_ID_EXIST);
        }
    }

}
